package cpr.command;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import cpr.DefaultCommandHandler;
import cpr.Printer;
import cpr.Rule;
import cpr.cache.CacheFactory;
import cpr.cache.FileCacheConfig;
import cpr.cache.ICache;
import cpr.cache.ICacheRecordReader;
import cpr.context.Context;
import cpr.context.ruleacceptor.GlobalRuleNrSetRuleAcceptor;
import cpr.data.HLVector;
import cpr.data.WorksetItem;
import data.ClusterDescriptor;

public class CmdWorksetLoad extends DefaultCommandHandler {
	public CmdWorksetLoad() {
		super("ws-load");
	}
    
    Set ruleNrsGlobal = new HashSet();
    List items = new ArrayList();
    int counter = 1;
    
    public void execute(String[] params) throws Exception {
        ICache cache = CacheFactory.createCache(FileCacheConfig.Factory.createForWorkset(getCommandContext().getContext().getCurrentWorksetContext()));
        if (!cache.exists()) {
            getCommandContext().println("not found!");
        }
        getCommandContext().getContext().getCurrentWorksetContext().clear();

        counter = 1;
        items = new ArrayList();
        
        ruleNrsGlobal = new HashSet();
        
        FileCacheConfig config =(FileCacheConfig)cache.getConfig();
        config.cacheReader = new ICacheRecordReader() {
            public void processCacheRecord(String[] st) {
                Integer ruleNrGlobal = null;
                HLVector vector = null;
                int size = -1;
                    ruleNrGlobal = new Integer(st[0]);
                    ruleNrsGlobal.add(ruleNrGlobal);
                    vector = new HLVector(Integer.parseInt(st[1]));
                    size = Integer.parseInt(st[2]);
                    
                    WorksetItem mi = new WorksetItem();
                    //mi.setId(counter++);
                    Rule dummyRule = new Rule();
                    dummyRule.ruleNrGlobal = ruleNrGlobal.intValue();
                    mi.setClusterDescriptor(new ClusterDescriptor(dummyRule, vector, size));
                    items.add(mi);
            }
            public void processMetadata(String metadata) {
                
            }
            
        };
        cache.load();
        
        Context ctx = getCommandContext().getContext();
        String csv_file  =  ctx.getPureDigitalDataFilePath();
        
        GlobalRuleNrSetRuleAcceptor ruleAcceptor = new GlobalRuleNrSetRuleAcceptor(ruleNrsGlobal);
        ruleAcceptor.setCacheRuleContext(ctx.getGlobalRuleCache());
        List hl_rules = ctx.getIOContext().readRulesFromPureDigitalFile(csv_file, ruleNrsGlobal.size(),ruleAcceptor);
        
        for (Iterator iter = hl_rules.iterator(); iter.hasNext();) {
            Rule aRule = (Rule) iter.next();
            for (Iterator iterator = items.iterator(); iterator
                    .hasNext();) {
                WorksetItem wi = (WorksetItem) iterator.next();
                if (wi.getClusterDescriptor().getRule().ruleNrGlobal == aRule.ruleNrGlobal) {
                    ClusterDescriptor mcd = (ClusterDescriptor)wi.getClusterDescriptor();
                    mcd.setRule(aRule);
                }
            }
        }

        for (Iterator iterator = items.iterator(); iterator
        .hasNext();) {
            WorksetItem wi = (WorksetItem) iterator.next();
            getCommandContext().getContext().getCurrentWorksetContext().addWorkSetItem(wi);
        }


        
        //getCommandContext().getContext().getCurrentWorksetContext().setWorksetItems(items);
        getCommandContext().executeInCurrentThread("ws");

    }
    
    
	public void TO_DELETE_execute(String[] params) throws Exception {
		String filename = getCommandContext().getContext().getCurrentWorksetContext().getWorksetFilePath();
		Printer.println("Loading "+filename);
		File file = new File(filename);
		if (!file.exists()) {
			getCommandContext().println("not found!");
		}
		Reader r = new FileReader(file);
		BufferedReader br = new BufferedReader(r);
		String s = null;
		Pattern spacePattern = Pattern.compile( "\\s" );
		int counter = 1;
		List items = new ArrayList();
		Set ruleNrsGlobal = new HashSet();
		
		do {
			s= br.readLine();
			if (s!=null) {
				String[] st = spacePattern.split(s);
				if (st.length!=3) {
					getCommandContext().println("format error: "+ s);
				} else {
		            
					Integer ruleNrGlobal = null;
					HLVector vector = null;
					int size = -1;
					try {
						ruleNrGlobal = new Integer(st[0]);
						ruleNrsGlobal.add(ruleNrGlobal);
						vector = new HLVector(Integer.parseInt(st[1]));
						size = Integer.parseInt(st[2]);
						
						WorksetItem mi = new WorksetItem();
						//mi.setId(counter++);
						Rule dummyRule = new Rule();
						dummyRule.ruleNrGlobal = ruleNrGlobal.intValue();
						mi.setClusterDescriptor(new ClusterDescriptor(dummyRule, vector, size));
						items.add(mi);
						
					} catch (Exception ex) {
						getCommandContext().println("format error: "+ s);
						return;
					}
				}
			}
		} while(s!=null);
		
		Context ctx = getCommandContext().getContext();
		String csv_file  =  ctx.getPureDigitalDataFilePath();
		
		GlobalRuleNrSetRuleAcceptor ruleAcceptor = new GlobalRuleNrSetRuleAcceptor(ruleNrsGlobal);
		List hl_rules = ctx.getIOContext().readRulesFromPureDigitalFile(csv_file, ruleNrsGlobal.size(),ruleAcceptor);
        
        for (Iterator iter = hl_rules.iterator(); iter.hasNext();) {
			Rule aRule = (Rule) iter.next();
			for (Iterator iterator = items.iterator(); iterator
					.hasNext();) {
				WorksetItem wi = (WorksetItem) iterator.next();
				if (wi.getClusterDescriptor().getRule().ruleNrGlobal == aRule.ruleNrGlobal) {
					ClusterDescriptor mcd = (ClusterDescriptor)wi.getClusterDescriptor();
					mcd.setRule(aRule);
				}
			}
		}

		for (Iterator iterator = items.iterator(); iterator
		.hasNext();) {
			WorksetItem wi = (WorksetItem) iterator.next();
			getCommandContext().getContext().getCurrentWorksetContext().addWorkSetItem(wi);
		}


        
		br.close();
		//getCommandContext().getContext().getCurrentWorksetContext().setWorksetItems(items);
		getCommandContext().executeInCurrentThread("ws");

	}
} 
